<template>
  <div class="chat-list">
    <!-- 搜索栏 -->
    <div class="search-section">
      <el-input
        v-model="searchKeyword"
        placeholder="搜索用户..."
        @input="handleSearch"
        clearable
        class="search-input"
      >
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-input>
    </div>

    <!-- 搜索结果 -->
    <div v-if="showSearchResults" class="search-results">
      <div class="search-results-header">
        <span>搜索结果</span>
        <el-button size="small" text @click="clearSearch">取消</el-button>
      </div>
      <div v-if="chatStore.searchResults.length === 0" class="no-results">
        <el-empty description="未找到相关用户" :image-size="60" />
      </div>
      <div
        v-for="user in chatStore.searchResults"
        :key="user.id"
        class="search-result-item"
        @click="startChatWithUser(user)"
      >
        <el-avatar :size="40" :src="user.avatar" class="user-avatar">
          {{ user.username.charAt(0).toUpperCase() }}
        </el-avatar>
        <div class="user-info">
          <div class="username">{{ user.username }}</div>
          <div class="user-role">{{ getUserRoleText(user.role) }}</div>
        </div>
        <el-button size="small" type="primary" plain>开始聊天</el-button>
      </div>
    </div>

    <!-- 聊天列表 -->
    <div v-else class="conversations-section">
      <div class="conversations-header">
        <span>聊天列表</span>
        <el-button size="small" text @click="refreshConversations">
          <el-icon><Refresh /></el-icon>
        </el-button>
      </div>
      
      <div v-if="chatStore.sortedConversations.length === 0" class="no-conversations">
        <el-empty description="暂无聊天记录" :image-size="80" />
        <el-button type="primary" @click="searchKeyword = ''">开始聊天</el-button>
      </div>
      
      <div
        v-for="conversation in chatStore.sortedConversations"
        :key="conversation.id"
        class="conversation-item"
        :class="{ active: conversation.other_user_id === chatStore.currentChatUser?.id }"
        @click="selectConversation(conversation)"
      >
        <el-avatar :size="48" :src="conversation.other_user.avatar" class="user-avatar">
          {{ conversation.other_user.username.charAt(0).toUpperCase() }}
        </el-avatar>
        
        <div class="conversation-info">
          <div class="conversation-header">
            <span class="username">{{ conversation.other_user.username }}</span>
            <span class="time">{{ formatTime(conversation.updated_at) }}</span>
          </div>
          <div class="conversation-preview">
            <span class="last-message">{{ getLastMessagePreview(conversation.last_message) }}</span>
            <el-badge 
              v-if="conversation.unread_count > 0" 
              :value="conversation.unread_count" 
              :max="99"
              class="unread-badge"
            />
          </div>
        </div>
        
        <div class="online-indicator" :class="{ online: conversation.other_user.online }"></div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useChatStore } from '@/stores/chat'
import { Search, Refresh } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'

const chatStore = useChatStore()

// 搜索相关
const searchKeyword = ref('')
const showSearchResults = computed(() => searchKeyword.value.trim().length > 0)

// 搜索处理
const handleSearch = () => {
  if (searchKeyword.value.trim()) {
    chatStore.searchUsers(searchKeyword.value.trim())
  }
}

const clearSearch = () => {
  searchKeyword.value = ''
  chatStore.searchResults = []
}

// 开始与用户聊天
const startChatWithUser = async (user: any) => {
  try {
    // 检查是否已有对话
    const existingConversation = chatStore.conversations.find(
      conv => conv.other_user_id === user.id
    )
    
    if (existingConversation) {
      chatStore.setCurrentChatUser(user)
    } else {
      // 创建新对话
      await chatStore.createConversation(user.id)
      chatStore.setCurrentChatUser(user)
    }
    
    clearSearch()
  } catch (error) {
    ElMessage.error('开始聊天失败')
  }
}

// 选择对话
const selectConversation = (conversation: any) => {
  chatStore.setCurrentChatUser(conversation.other_user)
}

// 刷新对话列表
const refreshConversations = () => {
  chatStore.loadConversations()
}

// 格式化时间
const formatTime = (timeStr: string) => {
  const date = new Date(timeStr)
  const now = new Date()
  const diff = now.getTime() - date.getTime()
  
  if (diff < 60000) { // 1分钟内
    return '刚刚'
  } else if (diff < 3600000) { // 1小时内
    return `${Math.floor(diff / 60000)}分钟前`
  } else if (diff < 86400000) { // 24小时内
    return `${Math.floor(diff / 3600000)}小时前`
  } else if (diff < 604800000) { // 7天内
    return `${Math.floor(diff / 86400000)}天前`
  } else {
    return date.toLocaleDateString()
  }
}

// 获取最后一条消息预览
const getLastMessagePreview = (message: any) => {
  if (!message) return '暂无消息'
  
  const content = message.content
  if (content.length > 20) {
    return content.substring(0, 20) + '...'
  }
  return content
}

// 获取用户角色文本
const getUserRoleText = (role: string) => {
  const roleMap: Record<string, string> = {
    student: '学生',
    mentor: '导师',
    tutor: '导师',
    enterprise: '企业',
    admin: '管理员'
  }
  return roleMap[role] || '用户'
}

onMounted(() => {
  chatStore.loadConversations()
  chatStore.loadOnlineUsers()
})
</script>

<style scoped>
.chat-list {
  height: 100%;
  display: flex;
  flex-direction: column;
  background: white;
}

.search-section {
  padding: 16px;
  border-bottom: 1px solid #e4e7ed;
}

.search-input {
  width: 100%;
}

.search-results {
  flex: 1;
  overflow-y: auto;
}

.search-results-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  background: #f8f9fa;
  border-bottom: 1px solid #e4e7ed;
  font-size: 14px;
  font-weight: 500;
}

.no-results {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 200px;
}

.search-result-item {
  display: flex;
  align-items: center;
  padding: 12px 16px;
  border-bottom: 1px solid #f0f0f0;
  cursor: pointer;
  transition: background-color 0.3s;
}

.search-result-item:hover {
  background: #f8f9fa;
}

.conversations-section {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.conversations-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  background: #f8f9fa;
  border-bottom: 1px solid #e4e7ed;
  font-size: 14px;
  font-weight: 500;
}

.no-conversations {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 16px;
}

.conversation-item {
  display: flex;
  align-items: center;
  padding: 12px 16px;
  border-bottom: 1px solid #f0f0f0;
  cursor: pointer;
  transition: all 0.3s;
  position: relative;
}

.conversation-item:hover {
  background: #f8f9fa;
}

.conversation-item.active {
  background: #e6f7ff;
  border-left: 3px solid #1890ff;
}

.user-avatar {
  margin-right: 12px;
  flex-shrink: 0;
}

.conversation-info {
  flex: 1;
  min-width: 0;
}

.conversation-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 4px;
}

.username {
  font-weight: 500;
  color: #1f2937;
  font-size: 14px;
}

.time {
  font-size: 12px;
  color: #9ca3af;
}

.conversation-preview {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.last-message {
  font-size: 13px;
  color: #6b7280;
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.unread-badge {
  margin-left: 8px;
}

.online-indicator {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background: #d1d5db;
  margin-left: 8px;
  flex-shrink: 0;
}

.online-indicator.online {
  background: #10b981;
}

.user-info {
  flex: 1;
  margin-left: 12px;
}

.user-info .username {
  font-weight: 500;
  color: #1f2937;
  font-size: 14px;
  margin-bottom: 2px;
}

.user-info .user-role {
  font-size: 12px;
  color: #6b7280;
}
</style>
